# 实现一个装饰器函数，用于缓存函数的执行结果。
def cache_result(func):
    cache = {}

    def inner(*args, **kwargs):
        cache_key = (args, tuple(sorted(kwargs.items())))
        if (cache_key in cache):
            return cache.get(cache_key)
        result = func(*args, **kwargs)
        cache[cache_key] = result
        return result, cache

    return inner


# @cache_result
# def square(num):
#     print(f"正在计算num的平方")
#     return num ** 2


# result, cache = square(2)
# _, cache = square(3)
# _, cache = square(5)
# print(cache)


# 编写一个装饰器函数，用于记录函数的调用次数。
def call_count(func):
    count = 0

    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        nonlocal count
        count += 1
        print(f"{func.__name__}函数被调用了{count}次")
        return result

    return wrapper


# @call_count
# def square(num):
#     print(f"正在计算num的平方")
#     return num ** 2
#
# square(1)
# square(2)
# square(3)
# 创建一个装饰器函数，使被装饰的函数只能在特定的时间段内执行。

import datetime


def time_limit(start_time, end_time):
    def outer(func):
        def wrapper(*args, **kwargs):
            now = datetime.datetime.now().time()
            if start_time < now < end_time:
                result = func(*args, **kwargs)
                return result
            else:
                print("当前时间不能执行")

        return wrapper

    return outer


@time_limit(start_time=datetime.time(9,0), end_time=datetime.time(23,59))
def test():
    print(f"只能在特定时间执行test")


test()
